package com.epam.task.web.service;

import com.epam.task.web.service.command.*;
import com.epam.task.web.util.logging.LoggerUtil;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

public class AbstractActionsFactory {

    LoggerUtil logger = new LoggerUtil(Logger.getLogger(AbstractActionsFactory.class));
    protected Map<String, Class<?>> map = defaultMap();

    public AbstractAction create(String actionName) {
        Class<?> aClass = (Class<?>) map.get(actionName);
        AbstractAction actionInstance = null;

        if (aClass == null) {
            throw new RuntimeException(getClass() + " was unable to find an action named '" + actionName + "'.");
        }

        try {
            actionInstance = (AbstractAction) aClass.newInstance();
        } catch (Exception exception) {
            logger.getExceptionTextFileLogger().error(exception);
        }

        return actionInstance;
    }

     protected Map<String, Class<?>> defaultMap() {
        Map<String, Class<?>> map = new HashMap<String, Class<?>>();

        // Filling map.
        map.put("loginAction", Login.class);
        map.put("logoutAction", Logout.class);
        map.put("showUsersAction", ShowUsers.class);
        map.put("showOrdersAction", ShowOrders.class);
        map.put("addOrderAction", AddOrder.class);
        map.put("editOrderAction", EditOrder.class);
        map.put("redirectAction", RedirectAction.class);

        return map;
    }

}
